package com.execdemo.demomasterservice.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.execdemo.demomasterservice.domain.Store;
import com.execdemo.demomasterservice.mapper.StoreMapper;
import com.execdemo.demomasterservice.service.StoreService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Slf4j
@RestController
@RequestMapping("/master")
public class StoreController {

    @Autowired
    private StoreService storeService;


    @Autowired
    private StoreMapper storeMapper;

    @Autowired
    private RedisTemplate redisTemplate;


    @GetMapping("/getStoreByCode/{code}")
    public Store getStoreByCode(@PathVariable("code") String code) {
        String storeJson = (String) redisTemplate.opsForValue().get("storeCode." + code);
        if (storeJson != null) {
            try {
                Store store = JSON.parseObject(storeJson, Store.class);
                log.info("从缓存中获取到数据{}", store);
                return store;
            } catch (Exception e) {
                log.error("redis缓存数据转换异常", e);
            }

        }
        return null;
    }

    @PostMapping("/saveFile")
    @ResponseBody
    public String saveStoreFile(@RequestParam("file") MultipartFile file) {

        try {
            Boolean savedExcel = storeService.saveExcel(file);

            if (savedExcel) {
                log.info("excel文件保存成功");
                return "Store Saved Successfully!!!";
            } else {
                log.info("excel文件保存失败");
                return "Store Saved failed!!!";
            }
        } catch (IOException e) {
            log.error("excel文件保存失败", e);
            return "Store Saved failed!!!";
        }




    }

    @PostMapping("/save")
    public String saveStore(@RequestBody Store store) {

        storeService.save(store);
        return "Store Saved Successfully!!!";
    }


    @PostMapping("/savetest")
    public String saveStoreTest() {
        System.out.println("saveStoreTest");
        return "Store Test";
    }

    @GetMapping("/renewRedis/{code}")
    public String renewRedis(@PathVariable("code") String code) {
        Boolean renewRedis = storeService.renewRedis(code);
        if (renewRedis) {
            log.info("redis更新成功");
            return "Store Renew Successfully!!!";
        } else {
            log.info("redis更新失败");
            return "Store Renew failed!!!";
        }
    }
}
